import Taro from "@tarojs/taro";
import apiUrl from "./urls";
import { post } from "./request/request";

import { getLocalToken } from "./userInfo";
import { handleStore, getStoreData } from "./init";
import { BINDSTAFFCARDID, ISBINDSTAFF } from "../constants/userInfo";

function goToUsercenter(cardId) {
  Taro.reLaunch({
    url: `/pages/tabbar/usercenter/usercenter?cardId=${cardId}&sourceType=6`,
  });
}

function goToHomePage() {
  Taro.reLaunch({
    url: `/pages/load/load`,
  });
}

function updateCache(cardId, isBind) {
  handleStore(ISBINDSTAFF, isBind);
  handleStore(BINDSTAFFCARDID, cardId);
  Taro.setStorageSync("isBindStaff", isBind);
  Taro.setStorageSync("bindStaffCardId", cardId);
}

let getStaffRelationshipPromise = null;

function getStaffRelationship() {
  if (getStaffRelationshipPromise) return getStaffRelationshipPromise;

  getStaffRelationshipPromise = post(
    apiUrl.queryStaffRelationship,
    {},
    {
      silentFail: true,
      ignoreResponseError: true,
    }
  );
  getStaffRelationshipPromise
    .then(() => (getStaffRelationshipPromise = null))
    .catch(() => (getStaffRelationshipPromise = null));
  return getStaffRelationshipPromise;
}

function checkStaffRelationship(isFromEntrancePage) {
  return new Promise((resolve, reject) => {
    const locIsBindStaff = Taro.getStorageSync("isBindStaff");
    const locBindCardId = Taro.getStorageSync("bindStaffCardId");
    const isLogined = !!getLocalToken();

    getStaffRelationship()
      .then((res) => {
        if (!res.data) {
          resolve(false);
          return;
        }

        const { cardId } = res.data;
        const bindCardId = cardId || null;
        const isBind = !!cardId;

        // 查询结果和本地一致，不做任何操作
        if (locIsBindStaff && locBindCardId === bindCardId && isLogined) {
          return;
        }

        updateCache(bindCardId, isBind, app);

        // 已绑定关系 且本地未存储绑定记录 或 存储的绑定记录和返回结果不一致
        if (isBind && isFromEntrancePage) {
          goToUsercenter(cardId);
        }

        // 本地存储不满足resolve条件 在这里resolve
        if (!locIsBindStaff || !isLogined) {
          resolve(isBind);
        }
      })
      .catch((error) => {
        // 如果与本地记录不一致 清除记录 如果是入口处的检查就返回到首页
        if (locIsBindStaff) {
          updateCache(null, false, app);
          if (isFromEntrancePage) {
            goToHomePage();
          }
        }
        reject(error);
      });

    updateCache(locBindCardId || null, locIsBindStaff || false, app);

    if (locIsBindStaff && isLogined) {
      if (isFromEntrancePage) goToUsercenter(locBindCardId);
      resolve(true);
    }
  });
}

function bindStaffRelationship(wxMobile, showLoading = false) {
  const u = getStoreData('userInfo');
  if (u.__isBindStaff) {
    return Promise.resolve(true);
  }

  return new Promise((resolve, reject) => {
    post(
      `${apiUrl.bindStaffRelationship}?wxMobile=${wxMobile}`,
      {},
      {
        showLoading,
        silentFail: true,
      }
    )
      .then((res) => {
        updateCache(res.data, true);
        resolve(true);
      })
      .catch((err) => reject(err));
  });
}

export { checkStaffRelationship, bindStaffRelationship };
